/** 数据新增、修改 */
import { isArray } from "util"
import { exportDefault, titleCase, deepClone } from "@/components/fortress-draggable/utils/index"
import ruleTrigger from "./ruleTrigger"

const baseUrl = process.env.VUE_APP_ROOT_URL_ENV

const units = {
	KB: "1024",
	MB: "1024 / 1024",
	GB: "1024 / 1024 / 1024",
}
let confGlobal
const inheritAttrs = {
	file: "",
	dialog: "inheritAttrs: false,",
}
let tbId

/**
 * 组装js 【入口函数】
 * @param {Object} formConfig 整个表单配置
 * @param {String} type 生成类型，文件或弹窗等
 * @param {String} configTbId 表单id
 * @param {String} recordId 记录id
 */
export function makeUpJs(formConfig, type, configTbId, recordId) {
	confGlobal = formConfig = deepClone(formConfig)
	tbId = configTbId
	const dataList = []
	const ruleList = []
	const optionsList = []
	const propsList = []
	const methodList = mixinMethod(type)
	const uploadVarList = []
	const created = []
	const mounted = []
	let intervalSecond = 60
	// recordId = '1468512834347020290'
	formConfig.fields.forEach(el => {
		buildAttributes(el, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created)
		//短信验证码特殊处理
		if (el.__config__.tag == "phone_sms") {
			dataList.push(`code_sms: '',`)
			intervalSecond = el.__config__.intervalSecond
		}
	})
	dataList.push(`id: '${recordId}'`)
	mounted.push(`this.resetForm()`)
	if (recordId) {
		mounted.push(`this.init('${tbId}','${recordId}')`)
	}
	buildBizMethod(methodList)
	const script = buildexport(
		formConfig,
		type,
		dataList.join("\n"),
		ruleList.join("\n"),
		optionsList.join("\n"),
		uploadVarList.join("\n"),
		propsList.join("\n"),
		[...methodList, ``].join("\n"),
		created.join("\n"),
		mounted.join("\n"),
		configTbId,
		intervalSecond,
	)
	confGlobal = null
	return script
}

// 构建组件属性
function buildAttributes(scheme, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created) {
	const config = scheme.__config__
	const slot = scheme.__slot__
	buildData(scheme, dataList)
	buildRules(scheme, ruleList)

	// 特殊处理options属性
	if (scheme.options || (slot && slot.options && slot.options.length)) {
		buildOptions(scheme, optionsList)
		if (config.dataType === "dynamic") {
			const model = `${scheme.__vModel__}Options`
			const options = titleCase(model)
			const methodName = `get${options}`
			buildOptionMethod(methodName, model, methodList, scheme)
			callInCreated(methodName, created)
		}
	}

	// 处理props
	if (scheme.props && scheme.props.props) {
		buildProps(scheme, propsList)
	}

	// 处理el-upload的action
	if (scheme.action && config.tag === "el-upload") {
		uploadVarList.push(
			`${scheme.__vModel__}Action: '${scheme.action}',
      ${scheme.__vModel__}fileList: [],`,
		)
		methodList.push(buildBeforeUpload(scheme))
		// 非自动上传时，生成手动上传的函数
		if (!scheme["auto-upload"]) {
			methodList.push(buildSubmitUpload(scheme))
		}
	}

	// 构建子级组件属性
	if (config.children) {
		config.children.forEach(item => {
			buildAttributes(item, dataList, ruleList, optionsList, methodList, propsList, uploadVarList, created)
		})
	}
}

// 在Created调用函数
function callInCreated(methodName, created) {
	created.push(`this.${methodName}()`)
}

// 混入处理函数
function mixinMethod(type) {
	const list = []
	const minxins = {
		file: confGlobal.formBtns
			? {
					submitForm: `submitForm() {
        this.$refs['${confGlobal.formRef}'].validate(valid => {
          if(valid) {
            let d={}
            d.tbId=this.tbId+'';
            d.formData=this.formData;
			d.params=this.params;
            let authorization = 'Bearer ' + localStorage.getItem("token") || "";
            this.$axios({
                method:'post',
                url:'${baseUrl}flowable/approves/saveData',
                headers: {
					        'Authorization': authorization
				        },
                data:d
            }).then((resp) =>{          //这里使用了ES6的语法
                if (resp.data.code == 0) { //请求成功返回的数据
                parent.dataeditfinish()
              } else {
                this.$message({
                  message: resp.data.msg,
                  type: "error",
                });
              }      
            }).catch((error) =>
                console.log(error)       //请求失败返回的数据
            )
          }else{
            return;
          }          
        })
      },`,
					resetForm: `resetForm() {
        this.$refs['${confGlobal.formRef}'].resetFields()
      },`,
					init: buildInitMethod(),
			  }
			: null,
		dialog: {
			onOpen: "onOpen() {},",
			onClose: `onClose() {
        this.$refs['${confGlobal.formRef}'].resetFields()
      },`,
			close: `close() {
        this.$emit('update:visible', false)
      },`,
			handelConfirm: `handelConfirm() {
        this.$refs['${confGlobal.formRef}'].validate(valid => {
          if(!valid) return
          this.close()
        })
      },`,
		},
	}

	const methods = minxins[type]
	if (methods) {
		Object.keys(methods).forEach(key => {
			list.push(methods[key])
		})
	}

	return list
}

// 构建data
function buildData(scheme, dataList) {
	const config = scheme.__config__
	if ("el-divider" !== config.tag && "span" !== config.tag) {
		if (scheme.__vModel__ === undefined) return
		const defaultValue = JSON.stringify(config.defaultValue)
		dataList.push(`${scheme.__vModel__}: ${defaultValue},`)
	}
}

// 构建校验规则
function buildRules(scheme, ruleList) {
	const config = scheme.__config__
	if (scheme.__vModel__ === undefined) return
	const rules = []
	if (ruleTrigger[config.tag]) {
		if (config.required) {
			const type = isArray(config.defaultValue) ? "type: 'array'," : ""
			let message = isArray(config.defaultValue) ? `请至少选择一个${config.label}` : scheme.placeholder
			if (message === undefined) message = `${config.label}不能为空`
			rules.push(`{ required: true, ${type} message: '${message}', trigger: '${ruleTrigger[config.tag]}' }`)
		}
		if (config.regList && isArray(config.regList)) {
			config.regList.forEach(item => {
				if (item.pattern) {
					rules.push(`{ pattern: ${eval(item.pattern)}, message: '${item.message}', trigger: '${ruleTrigger[config.tag]}' }`)
				}
			})
		}
		if (config.regList2 && config.regList2.id) {
			rules.push(`{ pattern: ${eval(config.regList2.pattern)}, message: '${config.regList2.message}', trigger: 'blur' }`)
		}
		ruleList.push(`${scheme.__vModel__}: [${rules.join(",")}],`)
	}
	//短信验证码
	if (config.tag == "phone_sms") {
		ruleList.push(`phone_sms: [{ required: true, message: '请填写手机号', trigger: 'change' },
    { required: true, message: '请填写手机号', trigger: 'blur' },
  { pattern: /^[1][3-9][0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],`)
		ruleList.push(`code_sms: [{ required: true, message: '请输入验证码', trigger: 'blur' }],`)
	}
}

// 构建options
function buildOptions(scheme, optionsList) {
	if (scheme.__vModel__ === undefined) return
	// el-cascader直接有options属性，其他组件都是定义在slot中，所以有两处判断
	let { options } = scheme
	if (!options) options = scheme.__slot__.options
	if (scheme.__config__.dataType === "dynamic") {
		options = []
	}
	let tag = scheme.__config__.tag
	//el-select、el-radio-group、el-checkbox-group 特殊处理 将value转字符串类型
	//"el-select" == tag || "el-radio-group" == tag || "el-checkbox-group" == tag
	if (["el-checkbox-group", "el-select", "el-radio-group"].includes(tag)) {
		if (options.length > 0) {
			options.forEach(o => {
				o.value = o.value + ""
			})
		}
	}
	const str = `${scheme.__vModel__}Options: ${JSON.stringify(options)},`
	optionsList.push(str)
}

function buildProps(scheme, propsList) {
	const str = `${scheme.__vModel__}Props: ${JSON.stringify(scheme.props.props)},`
	propsList.push(str)
}

// el-upload的BeforeUpload
function buildBeforeUpload(scheme) {
	const config = scheme.__config__
	const unitNum = units[config.sizeUnit]
	let rightSizeCode = ""
	let acceptCode = ""
	const returnList = []
	if (config.fileSize) {
		rightSizeCode = `let isRightSize = file.size / ${unitNum} < ${config.fileSize}
    if(!isRightSize){
      this.$message.error('文件大小超过 ${config.fileSize}${config.sizeUnit}')
    }`
		returnList.push("isRightSize")
	}
	if (scheme.accept) {
		acceptCode = `let isAccept = new RegExp('${scheme.accept}').test(file.type)
    if(!isAccept){
      this.$message.error('应该选择${scheme.accept}类型的文件')
    }`
		returnList.push("isAccept")
	}
	const str = `${scheme.__vModel__}BeforeUpload(file) {
    ${rightSizeCode}
    ${acceptCode}
    return ${returnList.join("&&")}
  },`
	return returnList.length ? str : ""
}

// el-upload的submit
function buildSubmitUpload(scheme) {
	const str = `submitUpload() {
    this.$refs['${scheme.__vModel__}'].submit()
  },`
	return str
}
/**
 * 构建业务组件
 * @param {*} methodList
 */
function buildBizMethod(methodList) {
	confGlobal.fields.forEach(el => {
		//地区
		if (el.__config__.tag == "fortress-region") {
			const str = `,${el.__vModel__}RegionHandler(regions, regionsInfo) {
      this.region = regions;
      if (regions.length == 3) {
        this.${confGlobal.formModel}.${el.__vModel__} = regions[0]+","+regions[1]+","+regions[2];
        this.${confGlobal.formModel}.${el.__vModel__}Name = regionsInfo[0].name+","+regionsInfo[1].name+","+regionsInfo[2].name;
      } else {
        this.${confGlobal.formModel}.${el.__vModel__} = "";
        this.${confGlobal.formModel}.${el.__vModel__}Name = "";
      }
    }`
			methodList.push(str)
			// 手机短信
		} else if (el.__config__.tag == "phone_sms") {
			const str = `,` + bindGetCodeMethod(el)
			methodList.push(str)
		}
	})
}
/**
 * 构建初始化方法
 */
function buildInitMethod() {
	let bizInit = ``
	confGlobal.fields.forEach(el => {
		if (el.__config__.tag == "fortress-region") {
			bizInit =
				bizInit +
				`let ${el.__vModel__} = [];
              if(this.${confGlobal.formModel}.${el.__vModel__}){
                ${el.__vModel__}=this.${confGlobal.formModel}.${el.__vModel__}.split(",");
              }
              this.$refs.${el.__vModel__}.init(${el.__vModel__});`
		}
	})
	return `init(tbId,id) {
		  let authorization = 'Bearer ' + localStorage.getItem("token") || "";
          //修改
          if (id) {
            this.formData.id=id;
            this.$axios({
                method:'get',
                url:'${baseUrl}flowable/approves/info',
				headers: {
					'Authorization': authorization
				},
                params:{
                  id:id,
                  tbId:'${tbId}'
                }
            }).then((resp) =>{          //这里使用了ES6的语法
                if (resp.data.code == 0) { //请求成功返回的数据
				if(resp.data.data.fortress_holiday) {
					resp.data.data.fortress_holiday = JSON.parse(resp.data.data.fortress_holiday)
				}
                this.formData = {
                    ...this.formData,
                    ...resp.data.data,
                  }
                  ${bizInit}
              } else {
                this.$message({
                  message: resp.data.msg,
                  type: "error",
                });
              }
            }).catch((error) =>
                console.log(error)       //请求失败返回的数据
            )}
        }`
}

//获取验证码
function bindGetCodeMethod(el) {
	let intervalSecond = el.__config__.intervalSecond ? el.__config__.intervalSecond : 60
	const str = `getCode(){
    let _this = this;    
    //校验手机号
    const reg = /^[1][3-9][0-9]{9}$/;
    if(!reg.test(this.${confGlobal.formModel}.phone_sms)){
      this.$message({
        message: "请填写正确的手机号",
        type: "error",
      });
      return;
    }
    //获取验证码
    let d ={
      tbId:this.tbId,
      phone_sms:this.${confGlobal.formModel}.phone_sms
    };
    this.$axios({
        method:'post',
        url:'${baseUrl}formManage/getCode',
        data:d
    }).then((resp) =>{          //这里使用了ES6的语法
        if (resp.data.code == 0) { //请求成功返回的数据
          this.$message({
            message: "发送成功",
            type: "success",
          });
      } else {
        this.$message({
          message: resp.data.msg,
          type: "error",
        });
      }
    }).catch((error) =>
        console.log(error)       //请求失败返回的数据
    )
    //显示验证码输入框
    this.smsCodeFlag = true;
    //按钮倒计时
    let timmer = setInterval(function () {
      _this.smsTimer = _this.smsTimer-1
      _this.codeSmsDesc = _this.smsTimer+"s"
      if (
        _this.smsTimer<=0
      ) {
        _this.smsTimer=${intervalSecond}
        _this.codeSmsDesc = "获取验证码"
        clearInterval(timmer);
      }
    }, 1000);
  }`
	return str
}

function buildOptionMethod(methodName, model, methodList, scheme) {
	const config = scheme.__config__
	const str = `${methodName}() {
    // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
    this.$axios({
      method: '${config.method}',
      url: '${config.url}'
    }).then(resp => {
      var { data } = resp
      this.${model} = data.${config.dataPath}
    })
  },`
	methodList.push(str)
}

// js整体拼接
function buildexport(conf, type, data, rules, selectOptions, uploadVar, props, methods, created, mounted, configTbId, intervalSecond) {
	const str = `
  ${exportDefault}{
  ${inheritAttrs[type]}
  components: {},
  props: [],
  data () {
    return {
      'tbId':'${configTbId}',
      'smsTimer':${intervalSecond},
      'smsCodeFlag':false,
      'codeSmsDesc':"获取验证码",
	  params: {},
      ${conf.formModel}: {
        ${data}
      },
      ${conf.formRules}: {
        ${rules}
      },
      ${uploadVar}
      ${selectOptions}
      ${props}
    }
  },
  computed: {},
  watch: {},
  created () {
    ${created}
  },
  mounted () {
    ${mounted}
  },
  methods: {
    ${methods}
  }
}`
	return str
}
